using System.Collections;
using UnityEngine;

public class UIJoystick : MonoBehaviour
{
	public Transform target;

	private float radius = 87f;

	public Vector2 position;

	public float distance;

	public float speed;

	private Vector3 initPos;

	private Vector3 initRot;

	public float xRotSpeed = 200f;

	public float yRotSpeed = 200f;

	public float rotDamp = 5f;

	public float yMinRotLimit = -10f;

	public float yMaxRotLimit = 60f;

	private float xDeg;

	private float yDeg;

	private Quaternion desiredRotation;

	private Quaternion currentRotation;

	private Quaternion rotation;

	public UISprite sprThumb;

	public MoveJoystick mvJoystick;

	private IEnumerator _return;

	private IEnumerator _moveJoystick;

	private bool isPress;

	public void OnDrag(Vector2 delta)
	{
		if (!GameController.instance.playerScript.isShock)
		{
			Vector3 origin = UICamera.currentCamera.ScreenPointToRay(UICamera.lastTouchPosition).origin;
			origin.z = 0f;
			target.position = Vector3.Lerp(target.position, origin, 4f * Time.deltaTime);
			float magnitude = target.localPosition.magnitude;
			if (magnitude > radius)
			{
				target.localPosition = Vector3.ClampMagnitude(target.localPosition, radius);
			}
			position = target.localPosition;
			position = position / radius * Mathf.InverseLerp(radius, 2f, 1f);
			distance = Vector3.Distance(position, Vector3.zero);
		}
	}

	private IEnumerator Return()
	{
		position = Vector3.zero;
		while (target.localPosition.magnitude > 0.01f)
		{
			target.localPosition = Vector3.Lerp(target.localPosition, Vector3.zero, 6f * Time.deltaTime);
			yield return null;
		}
	}

	public void OnPress(bool pressed)
	{
		if (pressed)
		{
			isPress = true;
			if (_return != null)
			{
				StopCoroutine(_return);
				_return = null;
			}
		}
		else
		{
			isPress = false;
			_return = Return();
			StartCoroutine(_return);
		}
	}

	private static float ClampAngle(float angle, float min, float max)
	{
		if (angle < -360f)
		{
			angle += 360f;
		}
		if (angle > 360f)
		{
			angle -= 360f;
		}
		return Mathf.Clamp(angle, min, max);
	}

	private void OnDrawGizmos()
	{
		Gizmos.color = Color.cyan;
	}

	private void OnDisable()
	{
		target.localPosition = Vector3.zero;
		position = Vector2.zero;
	}

	private IEnumerator StartMoveJoystick()
	{
		if (GameController.instance.playerScript.isShock)
		{
			yield break;
		}
		while (isPress)
		{
			Vector3 currentPos = UICamera.currentCamera.ScreenPointToRay(UICamera.lastTouchPosition).origin;
			currentPos.z = 0f;
			target.position = Vector3.Lerp(target.position, currentPos, 4f * Time.deltaTime);
			float length = target.localPosition.magnitude;
			if (length > radius)
			{
				target.localPosition = Vector3.ClampMagnitude(target.localPosition, radius);
			}
			position = target.localPosition;
			position = position / radius * Mathf.InverseLerp(radius, 2f, 1f);
			distance = Vector3.Distance(position, Vector3.zero);
			yield return null;
		}
	}
}
